package com.yige.web.controller

import com.mongodb.BasicDBObject
import com.mongodb.DBObject
import com.yige.common.ArgsUtil
import com.yige.common.MD5Util
import com.yige.common.ResultUtil
import com.yige.common.SystemConstant
import com.yige.common.ToDBObjectUtil
import com.yige.service.mongoService.MongoLessonService
import com.yige.service.mongoService.MongoSalaryService
import com.yige.service.mongoService.MongoStudentService
import com.yige.service.mongoService.MongoTeacherService
import com.yige.service.mongoService.MongoUserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody

/**
 * Created by sunhao on 2015/9/17 0017.
 */

@Controller
@RequestMapping("teacher")
class TeacherController {

    @Autowired
    MongoTeacherService teacherService
    @Autowired
    MongoLessonService lessonService
    @Autowired
    MongoStudentService studentService
    @Autowired
    MongoUserService userService
    @Autowired
    MongoSalaryService salaryService


    /*************控制器模块************/

    /**
     * 显示教师管理页面
     * @param model
     * @return
     */
    @RequestMapping("list.do")
    def list(Model model){
        def teacherList = teacherService.findList() as LinkedList
        model.addAttribute("teachers",teacherList)
        select(model)
        return "teacher/list"
    }

    /**
     * 多条件联合查询教师
     * @param model
     * @param name
     * @param lessonId
     * @return
     */
    @RequestMapping("find")
    def find(Model model, String name, String lessonId){
        def query = new BasicDBObject()
        if(!StringUtils.isEmpty(name)){
            query.append("name",~/${name}/)
        }
        if(!StringUtils.isEmpty(lessonId)){
            query.append("teach",[$in:[lessonId]]as BasicDBObject)
        }
        def teacherList = teacherService.findListByQuery(query) as LinkedList
        model.addAttribute("teachers",teacherList)
        select(model)
        return "teacher/list"
    }

    /**
     * 添加教师
     * @param name
     * @param phone
     * @param alipay
     * @param bank_num
     * @param bank
     * @return
     */
    @RequestMapping("addTeacher")
    @ResponseBody
    def addLessons(String name, String phone, String alipay, String bank_num, String bank){
        //创建教师信息
        def teach = new ArrayList() , students = new ArrayList(), salary = new ArrayList()
        Map<String,Object> teacherInfo = [_id:UUID.randomUUID().toString(),
                                          name:name,
                                         phone:phone,
                                         alipay:alipay,
                                         bank_num:bank_num,
                                         bank:bank,
                                         teach:teach,
                                         students:students,
                                         salary:salary]
        DBObject dbObject = ToDBObjectUtil.toDBObject(teacherInfo)
        addTeacherToUser(name,phone,teacherInfo.get("_id"))
        boolean flag = saveTeacher(dbObject)
        ResultUtil.recallAjax(flag)
    }

    /**
     * 删除教师
     * @param _ids
     * @return
     */
    @RequestMapping("delTeacher")
    @ResponseBody
    def delLesson(@RequestParam('_ids') List<String> _ids){
        //遍历删除教师
        boolean flag = false
        DBObject teacher, user
        _ids.each {_id->
            teacher = teacherService.findOneById(_id)
            user = userService.findOneByQuery([identity:_id]as BasicDBObject)
            userService.deleteOne(user._id)
            flag = teacherService.deleteOne(_id)
        }
        ResultUtil.recallAjax(flag)
    }

    /**
     * 修改教师
     * @param _id
     * @param name
     * @param phone
     * @param alipay
     * @param bank_num
     * @param bank
     * @return
     */
    @RequestMapping("updateTeacher")
    @ResponseBody
    def updateLesson(String _id, String name, String phone, String alipay, String bank_num, String bank){
        //创建教师信息
        def teach = teacherService.findAllLessonForTeacher(_id) ,
                students = teacherService.findAllStudentForTeacher(_id),
                salary = teacherService.findSalaryForTeacher(_id)
        Map<String,Object> TeacherInfo = [_id:_id,
                                         name:name,
                                         phone:phone,
                                         alipay:alipay,
                                         bank_num:bank_num,
                                         bank:bank,
                                         teach:teach,
                                         students:students,
                                         salary:salary]
        DBObject dbObject = ToDBObjectUtil.toDBObject(TeacherInfo)
        boolean flag = teacherService.updateOne(TeacherInfo._id,dbObject)
        ResultUtil.recallAjax(flag)
    }

    /**
     *
     * @param model
     * @param teacherId
     * @return
     */
    @RequestMapping("info")
    def findTeacher(Model model, String teacherId){
        def teacher = teacherService.findOneById(teacherId)
        def teacherMap = teacherArgs(teacher)
        model.addAttribute("teacher",teacherMap)
        return "teacher/info"
    }

    /**
     * 配置教师资源
     * @param teacherId
     * @param model
     * @return
     */
    @RequestMapping("configure")
    def configure(String teacherId, Model model){
        List<DBObject> lessonList = new ArrayList<>(), studentList = new ArrayList<>(),//定义教师拥有的课程和学生
        allLesson = lessonService.findList(),allStudent = studentService.findList(),//获得所有课程和学生
        noLesson,noStudent//定义教师未拥有课程和学生
        DBObject teacher = teacherService.findOneById(teacherId),lesson,student
        teacher.teach.each {
            lesson = lessonService.findOneById(it)
            if (allLesson.contains(lesson)){
                lessonList.add(lesson)
            }
        }
        teacher.students.each{
            student = studentService.findOneById(it)
            if(allStudent.contains(student)){
                studentList.add(student)
            }
        }
        if(lessonList.size() != 0){
            allLesson.removeAll(lessonList)
        }
        if(studentList.size() != 0){
            allStudent.removeAll(studentList)
        }
        noLesson = allLesson
        noStudent = allStudent
        model.addAttribute("teacher",teacher)
        model.addAttribute("lessons",lessonList)
        model.addAttribute("noLessons",noLesson)
        model.addAttribute("students",studentList)
        model.addAttribute("noStudents",noStudent)
        return "teacher/configure"
    }

    /**
     * 给教师绑定课程
     * @param _ids
     * @param teacherId
     * @return
     */
    @RequestMapping("bindLesson")
    @ResponseBody
    def bindLesson(@RequestParam('_ids') List<String> _ids,
                   @RequestParam('teacherId') String teacherId){
        boolean flag = false
        _ids.each {_id->
            flag = teacherService.bingLessonForTeacher(teacherId,_id)
        }
        ResultUtil.recallAjax(flag)
    }

    /**
     * 给教师解除课程
     * @param _ids
     * @param teacherId
     * @return
     */
    @RequestMapping("removeLesson")
    @ResponseBody
    def removeLesson(@RequestParam('_ids') List<String> _ids,
                     @RequestParam('teacherId') String teacherId){
        boolean flag = false
        _ids.each {_id->
            flag = teacherService.removeLessonForTeacher(teacherId,_id)
        }
        ResultUtil.recallAjax(flag)
    }

    /**
     * 给教师绑定学生
     * @param _ids
     * @param teacherId
     * @return
     */
    @RequestMapping("bindStudent")
    @ResponseBody
    def bindStudent(@RequestParam('_ids') List<String> _ids,
                    @RequestParam('teacherId') String teacherId){
        boolean flag = false
        _ids.each {_id->
            flag = teacherService.bindStudentForTeacher(teacherId,_id)
            flag = studentService.bindTeacherForStudent(_id,teacherId)
        }
        ResultUtil.recallAjax(flag)
    }

    /**
     * 给教师解除学生
     * @param _ids
     * @param teacherId
     * @return
     */
    @RequestMapping("removeStudent")
    @ResponseBody
    def removeStudent(@RequestParam('_ids') List<String> _ids,
                      @RequestParam('teacherId') String teacherId){
        boolean flag = false
        _ids.each {_id->
            flag = teacherService.removeStudentForTeacher(teacherId,_id)
            flag = studentService.removeTeacherForStudent(_id,teacherId)
        }
        ResultUtil.recallAjax(flag)
    }



    /*************方法模块***************/

    def saveTeacher(DBObject teacherInfo){
        ArgsUtil.checkArgs(teacherInfo)
        //判断教师是否存在
        def query = []as BasicDBObject
        query.append("name",teacherInfo.name)
        DBObject teacher_db = teacherService.findOneByQuery(query)
        if (teacher_db == null) {
            teacherService.insertOne(teacherInfo)
            return true
        }else {
            return false
        }
    }

    def select(Model model){
        def lessonList = lessonService.findList() as LinkedList
        model.addAttribute("lessons",lessonList)
        return model
    }

    def saveUser(DBObject userInfo){
        ArgsUtil.checkArgs(userInfo)
        // 判断用户名是否存在
        DBObject user_db = userService.findUserByName(userInfo.username)
        if (user_db == null) {
            // 用户名不存在，可以创建用户
            // 新增用户
            String md5Password = MD5Util.md5(userInfo.password)
            userInfo.put("password",md5Password)
            userInfo.put("registerTime",new Date(System.currentTimeMillis()))
            userService.insertOne(userInfo)
            return true
        } else {
            // 用户名已存在
            return false
        }
    }

    def addTeacherToUser(String name,String phone,String identity){
        List<String> role = new LinkedList<>()
        role.add("08903ddc-7414-4b63-9fd2-2e4b471ba5e9")
        def pwd = phone
        if(phone == null || StringUtils.isEmpty(phone)){
            pwd = SystemConstant.DEFAULT_PASSWORD
        }
        Map<String,Object> userInfo = [_id:UUID.randomUUID().toString(),
                                       username:name,
                                       password:pwd,
                                       email:phone,
                                       status:SystemConstant.USER_ON_JOB,
                                       role:role,
                                       identity:identity,
                                       degree:"teacher"
        ]
        DBObject dbObject = ToDBObjectUtil.toDBObject(userInfo)
        saveUser(dbObject)
    }

    def teacherArgs(DBObject teacher){
        Map<String, Object> teacherMap = new HashMap<>()
        List<DBObject> lessonList = teacherService.findAllLessonForTeacher(teacher._id),
                       lessons = new ArrayList<>(),
                       salaryList = teacherService.findSalaryForTeacher(teacher._id),
                       salaries = new ArrayList<>()
        lessonList.each {
            lessons.add(lessonService.findOneById(it))
        }
        salaryList.each {
            salaries.add(salaryService.findOneById(it))
        }
        teacherMap.put("_id",teacher._id)
        teacherMap.put("name",teacher.name)
        teacherMap.put("phone",teacher.phone)
        teacherMap.put("alipay",teacher.alipay)
        teacherMap.put("bank_num",teacher.bank_num)
        teacherMap.put("teach",lessons)
        teacherMap.put("salary",salaries)
        return teacherMap
    }

}
